<?php

class Home extends M_Controller
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页
     */
    public function index()
    {
        parent::_index();
    }

    // 盲盒列表
    public function blindList()
    {
        $page = $this->input->get('page');
        $pageSize = $this->input->get('pageSize') ?: 10;
        $result = $this->models('box')->boxList($page, $pageSize);
        apiSuccess(1, 'success', [
            'list' => array_map(function (&$item) {
                return $this->models('box')->boxTransfer($item);
            }, $result),
            'end' => count($result) < $pageSize
        ]);
    }

    // 盲盒详情
    public function boxInfo()
    {
        try {
            /**
             * @var $info //详情
             * @var $goods // 盲盒礼品
             */
            $result = $this->box($this->input->get('id'));
            extract($result);
            apiSuccess(1, 'success', [
                'info' => $this->models('box')->boxTransfer($info),
                'goods' => array_map(function (&$item) {
                    return $this->models('favorite')->favoriteTransfer($item);
                }, $goods),
                'status' => empty($info['blind_box']),
                'code' => $this->member['randcode']
            ]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 盲盒购买预支付
     */
    public function prepare()
    {
        try {
            $result = $this->box($this->input->get('id'));
            $openID = $this->models('member')->wxInfo($this->uid, 'openid');
            if (empty($openID)) {
                apiSuccess(40003, '无法获取openid');
            }
            apiSuccess(1, 'success', $result);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * 购买盲盒
     * 生成盲盒订单
     */
    public function buyBox()
    {
        try {
            $this->db->trans_begin();
            $result = $this->box($this->input->get('id'));
            $oid = $this->models('favorite')->addOrder($result, 'box');
            if ((int)$oid < 1) {
                throw new Exception('入库失败,请稍后重试');
            }
            if (empty($this->models('favorite')->addOrderGood($oid, $result))) {
                throw new Exception('订单商品添加失败', 1);
            }
            $payID = $this->models('system/pay')->create(
                $this->uid,
                $result['info']['price'],
                'box',
                $oid,
                '购买' . $result['info']['title']
            );
            // 将支付id 更新到订单
            $this->models('favorite')->operateOrder($oid, ['pay_id' => $payID]);
            // 进入订单队列
            $this->models('favorite')->addQueue($this->uid, $oid, 'box', $result['info']['id']);
            $this->db->trans_commit();
            apiSuccess(1, 'success', ['oid' => $oid, 'payId' => encrypt($payID, 'mutaoinc')]);
        } catch (Exception $e) {
            apiSuccess(0, $e->getMessage());
        }
    }


    /**
     * 最终支付完成后抽取盲盒
     */
    public function BlindBox()
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        try {
            $oid = $this->input->get('oid');
            if (empty($oid)) {
                throw new Exception('参数错误');
            }
            $this->db->trans_begin();
            $order = $this->models('favorite')->orderAndGood(
                $oid,
                'a.id,a.buy_uid,a.pay_status,a.order_status,a.order_price,b.cid,b.total'
            );
            if ($order['order_status'] == 9) {
                throw new Exception('效期内未付款, 订单已关闭');
            }
            if ($order['order_status'] <> 1) {
                throw new Exception('该订单已抽,请勿重新操作');
            }
            if ($order['pay_status'] <> 3) {
                throw new Exception('尚未付款成功,无法抽奖');
            }
            /**
             * @var  $info
             * @var $goods
             */
            $result = $this->box((int)$order['cid']);
            extract($result);
            require_once WEBPATH . 'web/libraries/Luck.php';
            $luckGood = (new Luck($goods))->begins();
            // 将抽中的奖品添加至自己获得的藏品列表
            $order['type'] = 'box';
            $order['cid'] = $luckGood['id'];
            $order['sn'] = $luckGood['buy_nums'] + 1;
            unset($luckGood['id']);
            $this->models('favorite')->gainCard($luckGood + $order);
            // 更新订单为完成状态
            $this->models('favorite')->operateOrder($order['id'], ['order_status' => 3]);
            // 给藏品增加销售量
            $this->models('favorite')->upSellNum($order['cid'], 'favorite');
            $this->db->trans_commit();
            $luckGood['thumb'] = dr_thumb($luckGood['thumb'], 500, 500);
            apiSuccess(1, 'success', $luckGood);
        } catch (Exception $e) {
            if ($e->getCode() == 1) {
                $this->db->trans_rollback();
            }
            apiSuccess(0, $e->getMessage());
        }
    }

    /**
     * @param  $id
     * @return array
     * @throws Exception
     */
    private function box($id): array
    {
        if ((int)$this->uid < 1) {
            apiSuccess(-4001, '请登录');
        }
        if ((int)$id < 1) {
            throw new Exception('参数错误');
        }
        ## 查看用户是否是被锁定购买
        $lockStatus = $this->models('favorite')->maxTimeAndNum($this->uid, strtotime("-1 hours"));
        if ($lockStatus['total'] >= 3 && time() - $lockStatus['end'] < 7200) {
            throw new Exception('您在1小时内同一账户产生' . $lockStatus['total'] . '个失效订单,锁定两小时');
        }
        $info = $this->models('box')->info($id, 'id,catid,title,blind_box,price,uid,author,nums,buy_nums,thumb');
        $goods = [];
        if ($info['blind_box']) {
            $goods = $this->models('favorite')->favoriteList(
                'id,catid,title,thumb,price,probability,nums,buy_nums',
                1,
                50,
                explode(',', $info['blind_box'])
            );
        }
        $nowNums = $info['buy_nums'] + 1;
        $member = $this->models('member')->uidInfo(['uid' => $this->uid], 'uid,name,username');
        return ['info' => $info, 'goods' => $goods, 'member' => $member, 'nums' => $nowNums];
    }
}